#!/usr/bin/env python
import os
import json
import sys
import urlparse
from urlparse import parse_qs
import mysql.connector
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('/etc/fileserver/config.ini')

MYSQL_CONFIG = {
    'host': config.get("mysql","host"),
    'user': config.get("mysql","user"),
    'password': config.get("mysql","password"),
    'database': config.get("mysql","database"),
    'charset': config.get("mysql","charset"),
    'port'   : config.get("mysql","port")
}

class FileStatus:
    NOT_SCANNED = 0
    SCANNING = 1
    NORMAL = 2
    EXCEPTION = 3

def save_file_to_database(file_uuid, file_name):
    cnx = mysql.connector.connect(**MYSQL_CONFIG)
    cursor = cnx.cursor()

    query = ("INSERT INTO filesecurity (file_uuid, file_name, status) "
             "VALUES (%s, %s, %s) "
             "ON DUPLICATE KEY UPDATE status = %s")
    data = (file_uuid, file_name, FileStatus.NOT_SCANNED, FileStatus.NOT_SCANNED)

    cursor.execute(query, data)
    cnx.commit()

    cursor.close()
    cnx.close()

query_string = os.environ.get('QUERY_STRING', '')
params = parse_qs(query_string)
file_name = params.get('file_name', [None])[0]
file_uuid = params.get('file_uuid', [None])[0]

if file_name and file_uuid:
    save_file_to_database(file_uuid, file_name)

response = {'status': 'success'}

print("Content-Type: application/json\n\n")
